Imports System.Web.Mail
Imports BikiSoft.Comm

Public Class frmConsultDownload
    Private m_Data(&HFFFF) As Byte
    Private m_UsbComm As Comm.UsbCommunicationHandle = Nothing

    Sub New(ByRef CommHandler As Comm.UsbCommunicationHandle)
        Me.InitializeComponent()
        m_UsbComm = CommHandler

    End Sub

    Private Sub cmdDownload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDownload.Click
        Dim iStart As Long = &H1000
        If thread_CheckIfOK(threadAction.TH_CMD) Then
            thread_Add(threadAction.TH_CMD)

reDo:       Dim f_ret As BK_return = DownloadConsult(m_Data, iStart)
            If f_ret <> BK_return.BK_OK Then
                Err_message(Err_Decode(f_ret))
                If MsgBox("Retry?", MsgBoxStyle.RetryCancel, "Resume Download") = MsgBoxResult.Retry Then GoTo reDo
            Else
                Try
                    If IsNothing(m_Data) Then 'm_Data.Length <> 65535 Then
                        m_Data = Nothing
                        cmdSave.Enabled = False
                    Else
                        cmdSave.Enabled = True
                    End If
                Catch
                End Try
            End If
            thread_Remove(threadAction.TH_CMD)
        End If
    End Sub

    Private Function DownloadConsult(ByRef oData As Byte(), ByRef iStart As Long) As BK_return
        Dim f_frame As Comm_Frame = Nothing
        Dim f_packet As Byte() = Nothing
        Dim f_return As Byte() = Nothing
        Dim f_cmd() As Byte = cv_BytesFromHex("361230C90000C90000C90000C90000F0")
        'Dim f_data(&HFFFF) As Byte
        Dim f_retry As Integer = 0
        Dim f_do_retry As Integer = 0
        Dim f_so_retry As Integer = 0
        Dim i As Long = iStart
        Dim f_index As Integer = 0
        Dim f_time As DateTime
        Dim f_returnCode As BK_return = BK_return.BK_OK

resend: If m_UsbComm.IsConnected AndAlso m_UsbComm.Initialised Then
            Try

                m_UsbComm.Timeout = 2000
                ' get into consult bypass mode
                f_frame = New Comm_Frame(Comm_Frame.BikiFrameType.ID_CONSULT_PASS, , Comm_Frame.BikiFrameAction.CMD_GO, , Comm_Frame.BikiFrameType.ID_LAST_COMMAND_STATUS)
                m_UsbComm.SendFrame(f_frame)

                Threading.Thread.Sleep(2000)
                ' send the initialisation
                f_frame = New Comm_Frame(Comm_Frame.BikiFrameType.ID_ECU, , , New Byte() {&H10, 1, &H30, &HFF, &HFF, &HEF}, Comm_Frame.BikiFrameType.ID_CONSULT_PASS)
                m_UsbComm.SendFrame(f_frame, f_return, True)

                m_UsbComm.Timeout = 1000

                f_time = Now()

                For i = iStart To &HFFFF Step 4
                    If Me.IsDisposed Then Exit Function

                    Me.Update()

                    f_index = -1000
                    f_do_retry = 0

                    ' Build the command
                    For s As Integer = 0 To 3
                        f_cmd((s * 3) + 4) = HIBYTE(s + i)
                        f_cmd((s * 3) + 5) = LOBYTE(s + i)
                    Next

                    f_frame = New Comm_Frame(Comm_Frame.BikiFrameType.ID_ECU, , , f_cmd, Comm_Frame.BikiFrameType.ID_CONSULT_PASS)
so_retry:           If m_UsbComm.SendFrame(f_frame, f_return, True, 0) = Comm_Frame.BikiFrameResponse.CMD_OK AndAlso _
                      Not IsNothing(f_return) AndAlso f_return.Length >= f_cmd(1) Then
do_try:                 'Console.WriteLine("Read: " & cv_StrFromBytes(f_return))

                        For s As Integer = 0 To f_return.Length - 14
                            If f_return(s) = 54 And _
                                f_return(s + 1) = f_cmd(4) And _
                                f_return(s + 2) = f_cmd(5) And _
                                f_return(s + 3) = 54 And _
                                f_return(s + 4) = f_cmd(7) And _
                                f_return(s + 5) = f_cmd(8) And _
                                f_return(s + 6) = 54 And _
                                f_return(s + 7) = f_cmd(10) And _
                                f_return(s + 8) = f_cmd(11) And _
                                f_return(s + 9) = 54 And _
                                f_return(s + 10) = f_cmd(13) And _
                                f_return(s + 11) = f_cmd(14) And _
                                f_return(s + 12) = &HFF And _
                                f_return(s + 13) = &H4 _
                            Then
                                f_index = s
                                'Console.WriteLine("Found Index")
                                Exit For
                            End If
                        Next

                        If f_index <> -1000 Then
                            Array.Copy(f_return, 14 + f_index, oData, i, 4)
                            If i Mod 16 = 0 Then Console.WriteLine()
                            Console.Write(cv_HexFromBytes(New Byte() {oData(i), oData(i + 1), oData(i + 2), oData(i + 3)}))
                            f_retry = 0
                            f_so_retry = 0
                        Else
                            f_frame = New Comm_Frame(Comm_Frame.BikiFrameType.ID_ECU, , , Nothing, Comm_Frame.BikiFrameType.ID_CONSULT_PASS)
                            If f_do_retry < 4 AndAlso m_UsbComm.SendFrame(f_frame, f_return, False, 0) And Not IsNothing(f_return) Then
                                f_do_retry += 1
                                GoTo do_try
                            End If

                            Console.WriteLine("Not Found Address 0x{0} Read: " & cv_StrFromBytes(f_return), Hex(i))
                            If pp(f_retry) < 10 Then
                                i -= 4
                            Else
                                f_returnCode = BK_return.BK_IO_ERROR_BIK
                                Exit Try
                            End If
                        End If

                        f_frame = New Comm_Frame(Comm_Frame.BikiFrameType.ID_ECU, , , New Byte() {&HCF, 1, &H30}, Comm_Frame.BikiFrameType.ID_CONSULT_PASS)
                        m_UsbComm.SendFrame(f_frame, f_return, True, 0)

                        Threading.Thread.Sleep(15)
                    ElseIf Not IsNothing(f_return) Then
                        'Console.WriteLine("blah: " & cv_StrFromBytes(f_return))
                    Else
                        If pp(f_retry) < 10 Then
                            i -= 4
                        Else
                            f_returnCode = BK_return.BK_IO_ERROR_BIK
                            Exit Try
                        End If
                    End If

                    If i >= pbDown.Minimum And i <= pbDown.Maximum And i Mod &H100 = 0 Then
                        pbDown.Value = i
                        Dim f_timespan As TimeSpan = Now().Subtract(f_time)

                        f_timespan = TimeSpan.FromTicks(((&HFFFF - i) / &H100) * f_timespan.Ticks)

                        pbDown.Caption = f_timespan.Minutes & ":" & f_timespan.Seconds & " remaining"

                        f_time = Now()
                    End If

                Next

                f_returnCode = BK_return.BK_OK
            Catch exComm As Comm_Exceptions

                BikiRom_Reset()
                If pp(f_retry) < 10 Then iStart = i : GoTo resend
                f_returnCode = BK_return.BK_IO_ERROR_BIK
            Catch exUsb As USB_exceptions
                BikiRom_Reset()
                If pp(f_retry) < 10 Then iStart = i : GoTo resend
                f_returnCode = BK_return.BK_IO_ERROR_USB
            End Try

            m_UsbComm.Flush()
            iStart = i
            Return f_returnCode
        Else
            Return BK_return.BK_FAILED_INIT
        End If
    End Function

    Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
        dlSave.Title = "Select File name to save to"
        dlSave.Filter = "*.bin Binary|*.bin"
        dlSave.AddExtension = True
        If dlSave.ShowDialog = Windows.Forms.DialogResult.OK Then
            arrayDump(m_Data, dlSave.FileName)
            cmdEmail.Enabled = True
        Else
            cmdEmail.Enabled = False
        End If

    End Sub

    Private Sub cmdEmail_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdEmail.Click
        Try
            'Dim oApp As New Outlook.Application
            'Dim oMsg As Outlook.MailItem
            'oMsg = oApp.CreateItem(Outlook.OlItemType.olMailItem)
            'Dim oAttachments As Outlook.Attachments = oMsg.Attachments
            'Dim oAttachment As Outlook.Attachment

            'oMsg.To = "Binaries@bikirom.com"
            'oMsg.Subject = "Binary files downloaded via consult"
            'oMsg.Body = "This is a downloaded binary. please integrate it into BikiSoft V2"

            'oAttachment = oAttachments.Add(dlSave.FileName, , oMsg.Body.Length + 1, GetFileName(dlSave.FileName))

            'oMsg.Send()
            'oApp = Nothing
            'oMsg = Nothing
            'oAttachment = Nothing
            'oAttachments = Nothing
        Catch
            MsgBox("Failed attempting to email " & dlSave.FileName & " Back to BikiRom.com" & Chr(10) & "Please send the file manualy via email back to Binaries@BikiRom.Com")
        End Try
    End Sub

End Class